package com.example.kafka.metric;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author lingGao
 */
@Component
@Slf4j
public class MetricReader {

    private static final String[] METRIC_FILE_LOCATIONS = new String[]{"classpath:metric/analog.xls",
            "classpath:metric/point.xls", "classpath:metric/string.xls"};

    private volatile List<MetricData> metricDataList;

    public List<MetricData> getMetricDataList() throws Exception {
        if (metricDataList == null) {
            synchronized (MetricReader.class) {
                if (metricDataList == null) {
                    List<MetricData> metricDataList = new ArrayList<>(105020);
                    DefaultResourceLoader resourceLoader = new DefaultResourceLoader(MetricReader.class.getClassLoader());
                    for (String metricFileLocation : METRIC_FILE_LOCATIONS) {
                        Resource resource = resourceLoader.getResource(metricFileLocation);
                        EasyExcel.read(resource.getInputStream(), MetricData.class, new ReadListener<MetricData>() {

                            @Override
                            public void invoke(MetricData metricData, AnalysisContext analysisContext) {
                                metricData.setTimestamp(System.currentTimeMillis());
                                metricDataList.add(metricData);
                            }

                            @Override
                            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                                log.info("read {} metric data", metricDataList.size());
                            }
                        }).sheet(0).doRead();
                    }
                    this.metricDataList = this.removeDuplicate(metricDataList);
                }
            }
        }
        return this.metricDataList;
    }

    private List<MetricData> removeDuplicate(List<MetricData> metricDataList) {
        HashMap<String, MetricData> map = new HashMap<>();
        for (MetricData metricData : metricDataList) {
            map.put(metricData.getMetric(), metricData);
        }
        return new ArrayList<>(map.values());
    }

}
